﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using ST.Application.RoleServices.Dtos;
using ST.Domain;
using ST.Domain.Entities;
using ST.Domain.IRepositories;

namespace ST.Application.RoleServices
{
    public class RoleService : IRoleService
    {
        private readonly IMapper _mapper;
        private readonly IRoleRepository _repository;

        public RoleService(IRoleRepository repository, IMapper mapper)
        {
            _repository = repository;
            _mapper = mapper;
        }

        /// <summary>
        ///     获取列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<RoleDto>> GetAllList()
        {
            var list = await _repository.GetAllListAsync();
            return _mapper.Map<List<RoleDto>>(list.OrderBy(o => o.Code));
        }

        /// <summary>
        ///     获取分页列表
        /// </summary>
        /// <param name="startPage">起始页</param>
        /// <param name="pageSize">页面大小</param>
        /// <returns></returns>
        public async Task<PagedList<RoleDto>> GetAllPageListAsync(int startPage, int pageSize)
        {
            var pageList = await _repository.LoadPageListAsync(startPage, pageSize, null, o => o.Code);
            return _mapper.Map<PagedList<RoleDto>>(pageList);
        }

        public async Task<bool> InsertAsync(RoleDto dto)
        {
            await _repository.InsertAsync(_mapper.Map<Role>(dto), false);
            return await _repository.SaveAsync();
        }

        public async Task<bool> UpdateAsync(RoleDto dto)
        {
            await _repository.UpdateAsync(_mapper.Map<Role>(dto), false);
            return await _repository.SaveAsync();
        }

        public async Task DeleteBatchAsync(List<Guid> ids)
        {
            await _repository.DeleteAsync(o => ids.Contains(o.Id));
        }

        public async Task DeleteAsync(Guid id)
        {
            await _repository.DeleteAsync(id);
        }

        public async Task<RoleDto> GetAsync(Guid id)
        {
            return _mapper.Map<RoleDto>(await _repository.GetAsync(id));
        }

        /// <summary>
        ///     根据角色获取权限
        /// </summary>
        /// <returns></returns>
        public List<Guid> GetAllMenuListByRole(Guid roleId)
        {
            return _repository.GetAllMenuListByRole(roleId);
        }

        /// <summary>
        ///     更新角色权限关联关系
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <param name="roleMenus">角色权限集合</param>
        /// <returns></returns>
        public bool UpdateRoleMenu(Guid roleId, List<RoleMenuDto> roleMenus)
        {
            return _repository.UpdateRoleMenu(roleId, _mapper.Map<List<RoleMenu>>(roleMenus));
        }
    }
}